﻿using System;
using System.Linq;
using HKEA.CMS.Core.DALFactory;
using HKEA.CMS.Core.IDAL;
using HKEA.CMS.Core.Models;

namespace HKEA.CMS.Core.DAL
{
    public class tbCodeGeneratorDAL:ItbCodeGeneratorDAL
    {
        HKEA_CMSEntities ctx;
        tbCodeGenerator entCodeGenerator;

        public tbCodeGeneratorDAL()
        {
            ctx = DataAccess.GetModelInstance();
        }

        public static tbCodeGeneratorDAL GetInstance()
        {
            return new tbCodeGeneratorDAL();
        }

        #region 公共方法

        public bool IsExist(string type)
        {
            if (ctx.tbCodeGenerators.Where(a => a.type == type).Count() > 0)
                return true;
            return false;
        }

        public bool IsExist(string type, int year, int month)
        {
            if (ctx.tbCodeGenerators.Where(a => a.type == type).Where(a => a.year == year).Where(a => a.month == month).Count() > 0)
                return true;
            return false;
        }

        public tbCodeGenerator GetEntByType(string type)
        {
            return ctx.tbCodeGenerators.Where(a=>a.type==type).FirstOrDefault();
        }

        public int InsertENT(tbCodeGenerator ent)
        {
            ent.created_at =ent.update_at= DateTime.Now;
            ctx.tbCodeGenerators.AddObject(ent);
            return ctx.SaveChanges();
        }

        public int UpdateENT(tbCodeGenerator ent)
        {
            entCodeGenerator = ctx.tbCodeGenerators.Where(a => a.id == ent.id).FirstOrDefault();
            if (entCodeGenerator != null)
            {
                entCodeGenerator.type = ent.type;
                entCodeGenerator.member_type = ent.member_type;
                entCodeGenerator.m_type_name = ent.m_type_name;
                entCodeGenerator.year = ent.year;
                entCodeGenerator.month = ent.month;
                entCodeGenerator.real_index = ent.real_index;
                entCodeGenerator.virtual_index = ent.virtual_index;
                entCodeGenerator.update_at = DateTime.Now;                
            }
            return ctx.SaveChanges();
        }

        #endregion
    }
}
